// 流式请求的聊天函数
export const chatWithDeepSeekStream = async (question, onDataReceived, onComplete, onError) => {
  try {
    const response = await fetch('https://api.deepseek.com/chat/completions', {
      method: "POST",
      headers: {
        'Authorization': 'Bearer sk-1fc3c0d9714942f4910ef002b20c638e', // 替换为你的 DeepSeek API 密钥
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: 'deepseek-chat', // 替换为实际使用的模型名称
        messages: [
          {
            role: 'user',
            content: `${question}`
          }
        ],
        stream: true,// 启用流式响应,
        temperature: 0.7
      })

    });
    console.log(response)
    let fullResponse = '';

    const reader = response.body.getReader();
    const decoder = new TextDecoder("utf-8");
    let buffer = "";
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      // 正确处理可能的多行数据
      const lines = buffer.split("\n");
      buffer = lines.pop(); // 保存最后不完整的行

      for (const line of lines) {
        if (line.trim() === "") continue; // 跳过空行

        if (line.startsWith("data: ")) {
          const dataStr = line.replace("data: ", "").trim();

          if (dataStr === "[DONE]") {
            onComplete(fullResponse);
            return;
          }

          try {
            const data = JSON.parse(dataStr);
            if (data.choices?.[0]?.delta?.content) {
              const content = data.choices[0].delta.content;
              fullResponse += content;
              onDataReceived(content);
            }
          } catch (err) {
            console.warn("解析JSON失败:", err, "原始数据:", dataStr);
          }
        }
      }

    }

  } catch (error) {
    console.error('设备故障诊断请求失败:', error);
    onError(error);
  }
};